# -*- coding:utf-8 -*-
import json

from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic import View
from django.contrib.auth.hashers import make_password
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

from users.models import UserProfile
from users.models import EmailVerifyRecode, Banner
from operation.models import UserCourse, UserFavorite, UserMessage
from organization.models import CourseOrg, Teacher
from courses.models import Course
from utils.email_send import send_register_email
from utils.mixin_util import LoginRequiredMixin

from .forms import LoginForm, RegisterForm, ForgetPwdForm, ModifyPwdForm, UploadImageForm, UserInfoForm


# 自定义用户登录的检验
class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            # 根据用户名或者邮箱获取用户
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        host = request.get_host()
        scheme = str(request.scheme)
        hosts = scheme + '://' + str(host)
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get('email', '')
            if UserProfile.objects.filter(email=email):
                return render(request, 'register.html', {'msg': '邮箱已经注册!'})
            password = request.POST.get('password', '')
            user_profile = UserProfile()
            user_profile.username = email
            user_profile.email = email
            user_profile.is_active = False
            # 对密码进行加密
            user_profile.password = make_password(password)
            # 保存数据
            user_profile.save()

            # 写入注册消息
            user_message = UserMessage()
            user_message.user = user_profile.id
            user_message.message = "欢迎注册慕学在线网"
            user_message.save()

            send_register_email(email, hosts)
            return render(request, "login.html")
        else:
            return render(request, "register.html", {"register_form": register_form})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 表单校验
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            # 获取用户名和密码
            user_name = request.POST.get('username', '')
            pass_word = request.POST.get('password', '')
            # 验证用户名和密码
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误!'})
        else:
            return render(request, 'login.html', {'login_form': login_form})


class LogoutView(View):
    """
    退出登录
    """

    def get(self, request):
        logout(request)
        return HttpResponseRedirect(reverse("index"))


class AciveUserView(View):
    def get(self, request, code):
        # 根据激活码获取记录
        all_recodes = EmailVerifyRecode.objects.filter(code=code)
        if all_recodes:
            for recode in all_recodes:
                email = recode.email
                user_profile = UserProfile.objects.get(email=email)
                user_profile.is_active = True
                user_profile.save()
        else:
            return render(request, 'active_fail.html')
        return render(request, 'login.html')


class ForgetPwdView(View):
    def get(self, request):
        forgetpwd_form = ForgetPwdForm()
        return render(request, 'forgetpwd.html', {'forgetpwd_form': forgetpwd_form})

    def post(self, request):
        host = request.get_host()
        scheme = str(request.scheme)
        hosts = scheme + '://' + str(host)
        forgetpwd_form = ForgetPwdForm(request.POST)
        if forgetpwd_form.is_valid():
            email = request.POST.get('email', '')
            send_register_email(email, hosts, 'forget')
            return render(request, 'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {"forgetpwd_form": forgetpwd_form})


class ResetPwdView(View):
    def get(self, request, code):
        all_recodes = EmailVerifyRecode.objects.filter(code=code)
        if all_recodes:
            for recode in all_recodes:
                email = recode.email
                return render(request, 'password_reset.html', {'email': email})
        else:
            return render(request, 'active_fail.html')
        return render(request, 'login.html')


class ModifyPwdView(View):
    """
    用户未登录修改用户密码
    """

    def post(self, request):
        modifypwd_form = ModifyPwdForm(request.POST)
        if modifypwd_form.is_valid():
            email = request.POST.get('email', '')
            pwd = request.POST.get('password1', '')
            pwd_again = request.POST.get('password2', '')
            if pwd == pwd_again:
                user = UserProfile.objects.get(email=email)
                user.password = make_password(pwd_again)
                user.save()
                return render(request, 'login.html')
            else:
                return render(request, 'password_reset.html', {'msg': '两次输入的密码不同'})
        else:
            email = request.POST.get("email", "")
            return render(request, 'password_reset.html', {'modifypwd_view': modifypwd_form.errors})


class UserInfoView(LoginRequiredMixin, View):
    """
    用户信息页面
    """

    def get(self, request):
        return render(request, 'usercenter-info.html', {})

    def post(self, request):
        """
        修改用户个人信息的提交
        :param request:
        :return:
        """
        userinfo_form = UserInfoForm(request.POST, instance=request.user)
        if userinfo_form.is_valid():
            userinfo_form.save()
            return HttpResponse('{"status":"success","msg":"修改个人信息成功"}', content_type='application/json')
        else:
            return HttpResponse(json.dumps(userinfo_form.errors), content_type='application/json')


class UploadImageView(LoginRequiredMixin, View):
    """
    用户头像修改
    """

    def post(self, request):
        # django中的文件类型放在request.FILES中
        image_from = UploadImageForm(request.POST, request.FILES)
        # image_from = UploadImageForm(request.POST, request.FILES, instance=request.user)
        if image_from.is_valid():
            # image_from.save()
            # 获取 modelfrom中的image
            image = image_from.cleaned_data['image']
            request.user.image = image
            request.user.image.save()
            return HttpResponse('{"status":"success","msg":"修改头像成功"}', content_type='application/json')


class UpdatePwdView(LoginRequiredMixin, View):
    """
    个人中心修改用户密码
    """

    def post(self, request):
        modifypwd_form = ModifyPwdForm(request.POST)
        if modifypwd_form.is_valid():
            pwd = request.POST.get('password1', '')
            pwd_again = request.POST.get('password2', '')
            if pwd == pwd_again:
                user = request.user
                user.password = make_password(pwd_again)
                user.save()
                return HttpResponse('{"status":"success","msg":"修改用户密码成功"}', content_type='application/json')
            else:
                return HttpResponse('{"status":"fail","msg":"两次输入的密码不一致"}', content_type='application/json')
        else:
            return HttpResponse(json.dumps(modifypwd_form.errors), content_type='application/json')


class SendEmailCodeView(LoginRequiredMixin, View):
    """
    发送邮箱验证码
    """

    def get(self, request):
        email = request.GET.get('email', '')
        if UserProfile.objects.filter(email=email):
            return HttpResponse('{"email":"邮箱已经存在"}', content_type='application/json')
        send_register_email(email, '', 'update_email')
        return HttpResponse('{"status":"success"}', content_type='application/json')


class UpdateEmailView(LoginRequiredMixin, View):
    """
    修改个人邮箱
    """

    def post(self, request):
        email = request.POST.get('email', '')
        code = request.POST.get('code', '')
        exist_recodes = EmailVerifyRecode.objects.filter(email=email, code=code, send_type='update_email')
        if exist_recodes:
            user = request.user
            user.email = email
            user.save()
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse('{"email":"验证码错误"}', content_type='application/json')


class MyCourseView(LoginRequiredMixin, View):
    """
    我的课程
    """

    def get(self, request):
        my_courses = UserCourse.objects.filter(user=request.user)
        return render(request, 'usercenter-mycourse.html', {
            'my_courses': my_courses,
        })


class MyFavOrgView(LoginRequiredMixin, View):
    """
    我的课程
    """

    def get(self, request):
        org_list = []
        myfav_orgs = UserFavorite.objects.filter(user=request.user, fav_type=2)
        for fav_org in myfav_orgs:
            org_id = fav_org.fav_id
            org = CourseOrg.objects.get(id=org_id)
            org_list.append(org)
        return render(request, 'usercenter-fav-org.html', {
            'org_list': org_list,
        })


class MyFavTeacherView(LoginRequiredMixin, View):
    """
    我的课程
    """

    def get(self, request):
        teacher_list = []
        myfav_teachers = UserFavorite.objects.filter(user=request.user, fav_type=3)
        for fav_teacher in myfav_teachers:
            teacher_id = fav_teacher.fav_id
            org = Teacher.objects.get(id=teacher_id)
            teacher_list.append(org)
        return render(request, 'usercenter-fav-teacher.html', {
            'teacher_list': teacher_list,
        })


class MyFavCourseView(LoginRequiredMixin, View):
    """
    我的课程
    """

    def get(self, request):
        course_list = []
        myfav_courses = UserFavorite.objects.filter(user=request.user, fav_type=1)
        for fav_course in myfav_courses:
            course_id = fav_course.fav_id
            course = Course.objects.get(id=course_id)
            course_list.append(course)
        return render(request, 'usercenter-fav-course.html', {
            'course_list': course_list,
        })


class MyMessageView(LoginRequiredMixin, View):
    def get(self, request):
        mymessages = UserMessage.objects.filter(Q(user=int(request.user.id)) | Q(user=0))

        unread_messages = UserMessage.objects.filter(user=int(request.user.id), has_read=False)
        for message in unread_messages:
            message.has_read = True
            message.save()
        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(mymessages, 5, request=request)
        messages = p.page(page)

        return render(request, 'usercenter-message.html', {
            'mymessages': messages
        })


class IndexView(View):
    # 首页
    def get(self, request):
        # 取出轮播图
        banners = Banner.objects.all().order_by('index')
        # 取出课程
        courses = Course.objects.filter(is_banner=False)[:6]
        banner_courses = Course.objects.filter(is_banner=True)[:3]
        # 课程机构
        course_orgs = CourseOrg.objects.all()[:15]
        return render(request, 'index.html', {
            'banners': banners,
            'courses': courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs,
        })


# 404
def page_not_found(request):
    response = render_to_response('404.html', {})
    response.status_code = 404
    return response


# 500
def page_error(request):
    response = render_to_response('500.html', {})
    response.status_code = 500
    return response
